package com.zhouxiaoge.transaction.jms.web;

import com.zhouxiaoge.transaction.jms.service.CustomerService;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/customer")
public class CustomerResource {

    private final JmsTemplate jmsTemplate;
    private final CustomerService customerService;

    public CustomerResource(JmsTemplate jmsTemplate, CustomerService customerService) {
        this.jmsTemplate = jmsTemplate;
        this.customerService = customerService;
    }

    /**
     * JMS  session实例
     * 使用 @JmsListener(destination = "customer:msg:new") 监听消息，事务提交时在整个方法结束时
     * 直接使用 jmsTemplate.convertAndSend("customer:msg:reply", reply);事务提交时在当前调用时
     * 产生不通结果：
     * 如果方法异常出错，使用@JmsListener监听消息，会在出错时回滚事务，消息提交不成功
     * 而直接调用jmsTemplate.convertAndSend，会在调用时就发送消息，不回滚，消息会提交成功。
     */
    // 直接调用-监听@JmsListener
    @PostMapping("/message1/listen")
    public void createMsgWithListener(@RequestParam String msg) {
        jmsTemplate.convertAndSend("customer:msg:new", msg);
    }

    // 转发调用-jmsTemplate.convertAndSend
    @PostMapping("/message1/direct")
    public void createMsgDirect(@RequestParam String msg) {
        customerService.handle(msg);
    }

    /**
     *Jms JmsTransactionManager
     */


    @PostMapping("/message2/listen")
    public void createMsg2WithListener(@RequestParam String msg) {
        jmsTemplate.convertAndSend("customer:msg2:new", msg);
    }

    @PostMapping("/message2/direct")
    public void createMsg2Direct(@RequestParam String msg) {
        customerService.handle2(msg);
    }

    @GetMapping("/message")
    public String getMsg() {
        jmsTemplate.setReceiveTimeout(2000);
        Object reply = jmsTemplate.receiveAndConvert("customer:msg:reply");
        return String.valueOf(reply);
    }
}
